package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.PermissionDao;
import com.huike.pmps.dao.RoleDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.dto.role.RolePermissionDTO;
import com.huike.pmps.model.entity.Permission;
import com.huike.pmps.model.entity.Role;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao roleDao;
    @Autowired
    PermissionDao permissionDao;


    @Override
    public Result insertOne(String name) {
        Role role = Role.builder().roleName("ROLE_USER").name(name).state(1).createTime(new Date()).build();
        roleDao.insert(role);
        return Result.success();
    }

    @Override
    public Result deleteByRoleId(Integer roleId) {
        if (roleId == GlobalConstants.SYSTEM_ROLE_ADMIN ||
                roleId == GlobalConstants.SYSTEM_ROLE_REGION ||
                roleId == GlobalConstants.SYSTEM_ROLE_PROVINCE ||
                roleId == GlobalConstants.SYSTEM_ROLE_COURSE_CHARGE ||
                roleId == GlobalConstants.SYSTEM_ROLE_WAREHOUSE)
            return Result.failure("系统内置角色不可删除");

        //删除角色
        roleDao.deleteById(roleId);
        //删除角色权限关系对应表中的数据
        roleDao.deleteRoleAndPermissionRelationByRoleId(roleId);
        return Result.success();
    }

    @Override
    public Result updateByRoleId(Integer roleId, String name) {
        Role role = Role.builder().id(roleId).name(name).build();
        roleDao.updateById(role);
        return Result.success();
    }

    @Override
    public Result updateStateByRoleId(Integer roleId, Integer state) {
        Role role = Role.builder().id(roleId).state(state).build();
        roleDao.updateById(role);
        return Result.success();
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, String name, Short state) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name))
            queryWrapper.like("name", name);
        if (state != null)
            queryWrapper.eq("state", state);
        Page<Role> page = new Page<Role>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<Role> rolePage = roleDao.selectPage(page, queryWrapper);

        if (rolePage.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(rolePage.getCurrent()).pageSize(rolePage.getSize())
                    .total(rolePage.getTotal()).rows(rolePage.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }
    }

    @Override
    public Result insertRoleAndPermissionRelation(Integer roleId, String permissionIds) {
        List<RolePermissionDTO> rolePermissionDTOList = new ArrayList<>();
        for (String permissionId : permissionIds.split(",")) {
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO(roleId, Integer.valueOf(permissionId));
            rolePermissionDTOList.add(rolePermissionDTO);
        }
        //根据角色roleId，删除原有(角色权限关系表)中的数据
        roleDao.deleteRoleAndPermissionRelationByRoleId(roleId);
        //添加新的角色权限关系数据
        roleDao.insertRoleAndPermissionRelation(rolePermissionDTOList);
        return Result.success();
    }

    @Override
    public Result selectOneById(Integer roleId) {
        Role role = roleDao.selectById(roleId);
        if (role != null) {
            List<Permission> permissions = permissionDao.findByRoleId(roleId);
            List<Integer> permissionsIds = new ArrayList<>();
            for (Permission permission : permissions) {
                permissionsIds.add(permission.getId());
            }
            role.setPermissions(permissions);
            role.setPermissionsIds(permissionsIds);
        }
        return Result.success(role);
    }
}
